import re

from django.http import JsonResponse, HttpResponse
from django.shortcuts import render
from django.views import View
from .models import User, Address
import json

# Create your views here.

class UsernameCountView(View):

    def get(self, request, username):

        # mobile = User.onjects.filter(mobile=mobile).count()
        count = User.objects.filter(username=username).count()
        return JsonResponse({'code': 200, 'count': count})


class MobileCountView(View):
    def get(self, request, mobiles):
        count = User.objects.filter(mobile=mobiles).count()
        return JsonResponse({'code': 200, 'count': count})

class RegisterView(View):


    def post(self, request):
        # 获取数据
        json_obj = request.body
        json_str = json_obj.decode()
        json_dict = json.loads(json_str)

        username = json_dict.get('username')
        password = json_dict.get('password')
        password2 = json_dict.get('password2')
        mobile = json_dict.get('mobile')
        allow = json_dict.get('allow')

        # 验证数据
        if allow != True:
            return JsonResponse({'code': 500, 'data': 'not allow'})

        # 用户名和手机号不能重复的验证
        # old_use = User.objects.filter(username=username)
        # old_mobile = User.objects.filter(mobile=mobile)
        #
        # old_username = old_use.username
        # if old_mobile:
        #     return JsonResponse({'code': 408, 'data': 'The username or mobile is exist'})



        if not re.match('[a-zA-Z0-9]{5,20}', username):
            return JsonResponse({'code': 404, 'data:': 'The username or password is win'})


        if password != password2:
            return JsonResponse({'code':'404', 'data:': 'The username or password is win'})

        user = User.objects.create_user(username=username, password=password, mobile=mobile)

        # 登陆状态的保持。保存在session
        from django.contrib.auth import login
        login(request, user)

        return JsonResponse({'code': 0, 'data': 'ok'})



class LoginView(View):

    def post(self, request):

        # 接受数据
        json_str = request.body
        json_obj = json.loads(json_str)
        username = json_obj.get('username')
        password = json_obj.get('password')
        remembered = json_obj.get('remembered')

        # 验证数据
        if not all([username, password]):
            return JsonResponse({'code': 490, 'errmsg': '参数不全'})

        if re.match('1[3-9]\d{9}', username):
            User.USERNAME_FIELD = 'mobile'
        else:
            User.USERNAME_FIELD = 'username'


        from django.contrib.auth import authenticate
        # 如果验证正确拿到数据，拿不到返回None
        user = authenticate(username=username, password=password)
        if user is None:
            return JsonResponse({'code': 400, 'errmsg': '账号或密码错误'})

        from django.contrib.auth import login
        login(request, user)





        if remembered :
            request.session.set_expiry(None)    # 默认两周
        else:
            request.session.set_expiry(0)

        response = JsonResponse({'code': 0, 'errmsg': 'ok'})
        response.set_cookie('username', username)

        from ..carts.utils import merge_cookie_to_redis

        response = merge_cookie_to_redis(request, response)

        return response




from django.contrib.auth import logout

class LogoutView(View):

    def delete(self, request):

        logout(request)

        response = JsonResponse({'code': 0, 'errmsg': 'ok'})
        response.delete_cookie('username')
        return response




# from django.contrib.auth.mixins import LoginRequiredMixin, AccessMixin
# class LoginRequiredJSONMixin(AccessMixin):
#     """Verify that the current user is authenticated."""
#
#     def dispatch(self, request, *args, **kwargs):
#         if not request.user.is_authenticated:
#             return JsonResponse({'code': 400, 'errmsg': '没有登陆'})
#         return super().dispatch(request, *args, **kwargs)


from utils.views import LoginRequiredJSONMixin


class CenterView(LoginRequiredJSONMixin, View):
    def get(self, request):
        info_data = {
            'username': request.user.username,
            'email': request.user.email,
            'mobile': request.user.mobile,
            'email_active': request.user.email_active,
        }

        return JsonResponse({'code': 0, 'info_data': info_data})


class EmailView(LoginRequiredJSONMixin, View):
    def put(self, request):

        json_str = request.body.decode()
        json_dict = json.loads(json_str)
        email = json_dict.get('email')

        # 验证数据，正则

        # 保存邮箱地址
        user = request.user
        user.email = email
        user.save()

        # 邮件用user.id来确定具体用户
        from meiduo_mall.settings import SECRET_KEY
        token = request.user.id


        # 发送激活邮件
        from django.core.mail import send_mail
        from celery_tasks.email.tasks import celery_send_email

        vreify_url = 'htpp://www.meiduo.site:8080/success_verify_email.html?token=%s' % token
        subject = '主题'           # 主题
        message = '爱青青'            # 内容
        from_email = '美多商城<18290922922@163.com>'         # 发件人
        recipient_list = ['1198681842@qq.com']     # 收件人列表
        html_message = '<p>尊敬的用户您好！</p>' \
                       '<p>感谢您使用美多商城</p>'\
                       '<p>您的邮箱为：%s 。请点击此链接激活你的邮箱：</p>'\
                       '<p><a href=%s>%s<a></p>' % (email, vreify_url, vreify_url)           # 发送html文件

        # send_mail(subject=subject, message=message, from_email=from_email, recipient_list=recipient_list, html_message=html_message)
        celery_send_email.delay(subject, message, from_email, recipient_list, html_message)


        return JsonResponse({'code': 0, 'errmsg': 'ok'})



class Emails_Verification(View):
    def put(self, request):
        token = request.GET.get('token')
        if token is None:
            return JsonResponse({'code': 400, 'errmsg': '缺失参数token'})
        id = token
        user = User.objects.get(id=id)
        user.email_active = True
        user.save()
        return JsonResponse({'code': 0})


class AddressCreateView(LoginRequiredJSONMixin, View):


    def post(self, request):

        json_str = request.body.decode()
        json_dict = json.loads(json_str)
        receiver = json_dict.get('receiver')
        province_id = json_dict.get('province_id')
        city_id = json_dict.get('city_id')
        district_id = json_dict.get('district_id')
        place = json_dict.get('place')
        mobile = json_dict.get('mobile')
        tel = json_dict.get('tel')
        email = json_dict.get('email')

        user = request.user
        # 验证数据
        # if all() is None:
        #     return JsonResponse({'code': 398})

        address = Address.objects.create(
            user=user,
            title=receiver,
            receiver=receiver,
            province_id=province_id,
            city_id=city_id,
            district_id=district_id,
            place=place,
            mobile=mobile,
            tel=tel,
            email=email
        )

        address_dict = {
            'id': address.id,
            "title": address.title,
            "receiver": address.receiver,
            "province": address.province.name,
            "city": address.city.name,
            "district": address.district.name,
            "place": address.place,
            "mobile": address.mobile,
            "tel": address.tel,
            "email": address.email
        }


        return JsonResponse({'code': 0, 'errmsg': 'ok', 'address': address_dict})

    def put(self, request, id):

        user = request.user

        json_dict = json.loads(request.body.decode())
        user = user,
        title = json_dict.get('receiver')
        receiver = json_dict.get('receiver')
        province_id = json_dict.get('province_id')
        city_id = json_dict.get('city_id')
        district_id = json_dict.get('district_id')
        place = json_dict.get('place')
        mobile = json_dict.get('mobile')
        tel = json_dict.get('tel')
        email = json_dict.get('email')

        address_update = Address.objects.get(id=id)
        address_update.title = title
        address_update.receiver = receiver
        address_update.province_id = province_id
        address_update.city_id = city_id
        address_update.district_id = district_id
        address_update.place = place
        address_update.mobile = mobile
        address_update.tel = tel
        address_update.email = email
        address_update.save()

        return JsonResponse({'code': 0})




class AddressView(LoginRequiredJSONMixin, View):
    def get(self, request):
        user = request.user
        addresses = Address.objects.filter(user=user)
        addresses_list = []
        for address in addresses:
            addresses_list.append({
                'id': address.id,
                "title": address.title,
                "receiver": address.receiver,
                "province": address.province.name,
                "city": address.city.name,
                "district": address.district.name,
                "place": address.place,
                "mobile": address.mobile,
                "tel": address.tel,
                "email": address.email
                 })

        return JsonResponse({'code': 0, 'addresses': addresses_list})


class DeleteAddress(LoginRequiredJSONMixin, View):
    # 删除地址
    def delete(self, request, id):

        delete_address = Address.objects.filter(id=id)
        delete_address.delete()
        delete_address.save()

        return JsonResponse({'code': 0})



# 更改地址标题名称  put  /addresses/' + this.addresses[index].id + '/title/

class TitleView(LoginRequiredJSONMixin, View):

    def put(self, request, id):

        json_dict = json.loads(request.body.decode())
        title_update = json_dict.get('title')
        title_address = Address.objects.get(id=id)
        title_address.title = title_update
        title_address.save()
        input_title = title_address.title

        return JsonResponse({'code': 0})    #, 'input_title': input_title})





from django_redis import get_redis_connection
from goods.models import SKU

class UserHistoryView(LoginRequiredJSONMixin, View):

    def post(self, request):

        user = request.user

        json_dict = json.loads(request.body.decode())

        sku_id = json_dict.get('sku_id')
        redis_cli = get_redis_connection('history')
        try:
            sku = SKU.objects.get(id=sku_id)
        except Exception as e:
            return JsonResponse({'code': 400, 'errmsg': '没有数据'})

        redis_cli.lrem('history_%s' % user.id, 0, sku_id)
        redis_cli.lpush('history_%s' % user.id, sku_id)

        # 只保存五条记录
        redis_cli.ltrim('history_%s' % user.id, 0, 4)

        return JsonResponse({'code': 0, 'errmsg': 'ok'})


    def get(self, request):
        # 1. 连接redis
        redis_cli = get_redis_connection('history')
        # 2. 获取redis数据（[1,2,3]）
        ids = redis_cli.lrange('history_%s' % request.user.id, 0, 4)
        # [1,2,3]
        # 3. 根据商品id进行数据查询
        history_list = []
        for sku_id in ids:
            sku = SKU.objects.get(id=sku_id)
            # 4. 将对象转换为字典
            history_list.append({
                'id': sku.id,
                'name': sku.name,
                'default_image_url': sku.default_image.url,
                'price': sku.price
            })

        # 5. 返回JSON
        return JsonResponse({'code': 0, 'errmsg': 'ok', 'skus': history_list})









